<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <Search :allOpts="formInline.allOpts" v-model="formInline.cOpts" @blur="search"></Search>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleAdd" :disabled="butStatus.add"  type="success">创建</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="handleUpdate" :disabled="butStatus.update">修改</el-button>
        </el-form-item>

        <el-form-item>
          <el-button @click="handleDelete" :disabled="butStatus.rm" type="danger">删除</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="info"  @click="exportTask">导出</el-button>
        </el-form-item>

        <el-form-item>
          <el-upload
            :action="uploadUrl"
            :headers="headers"
            :data="uploadBody"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :show-file-list=false
            :file-list="fileList"
            multiple>
            <el-button type="info">导入</el-button>
          </el-upload>

        </el-form-item>


        <el-form-item>
          <el-button type="info" @click="gotopage(33)">Yarn应用</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="info" @click="gotopage(32)">数据源管理</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="gotopage(311)" type="info">任务信息</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="gotopage(3110)" type="info">分组</el-button>
        </el-form-item>

      </el-form>
    </el-col>
    <!--列表-->
    <el-table
      v-loading="listLoading"
      :data="tableData"
      border
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column label="模板名称">
        <template scope="scope">
          <el-popover
            placement="right"

            width="200"
            trigger="hover"
            :content="scope.row.task_desc||'暂无描述'">
            <router-link slot="reference" :to="{ path: `page311/${scope.row.user_task_id}`, query: {type: `${scope.row.task_run_component_type}`}}">{{scope.row.user_task_name}}</router-link>
          </el-popover>

        </template>
      </el-table-column>
      <el-table-column label="组名称" prop="task_group_name"></el-table-column>

      <el-table-column label="模版类型">
        <template scope="scope">
          <span>{{scope.row.task_run_component_type | taskType}}</span>
        </template>
      </el-table-column>
      <el-table-column v-for="item in tableTitle" :prop="item.key" :label="item.name">
      </el-table-column>
      <el-table-column label="状态">
        <template scope="scope">

          <span v-if="scope.row.task_status!='3'">{{scope.row.task_status | toSta}}</span>
          <span v-if="scope.row.task_status=='3'">
            <el-tag :type="scope.row.task_result=='2'?`danger`:`success`">
              {{scope.row.task_result | taskResult}}
            </el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button
            v-if="scope.row.task_run_type == 1"
            type="primary"
            size="small"
            @click="changeStart(scope)"
            :disabled="( scope.row.task_status == 1 || scope.row.task_status == 4)">启动
          </el-button>
          <el-button v-if="scope.row.task_run_type == 2" :type="scope.row.status=='1'?'info':'warning'" size="small"
                     @click="changeStart(scope)">{{scope.row.status | timerBtn}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <el-col :span="24" class="toolbar" style="padding-bottom:10px;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.start_index"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pagination.page_count"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.count"
        style="float:right"></el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog :title="formTitle" v-model="dialogFormVisible" size="tiny" @close="resetForm">
      <el-form :model="form" :rules="rules" ref="form" :label-width="formLabelWidth" label-position="left">
        <el-form-item label="类型选择">
          <el-radio-group v-model="form.type">
            <el-radio @click.native="editinps('Spark')" label="Spark"
                      :disabled="editinpDisabled.type"></el-radio>
            <el-radio @click.native="editinps('MapReduce')" label="MapReduce"
                      :disabled="editinpDisabled.type"></el-radio>
            <el-radio @click.native="editinps('Hive')" label="Hive"
                      :disabled="editinpDisabled.type"></el-radio>
            <el-radio @click.native="editinps('Sqoop')" label="Sqoop"
                      :disabled="editinpDisabled.type"></el-radio>
            <el-radio @click.native="editinps('Shell')" label="Shell"
                      :disabled="editinpDisabled.type"></el-radio>
            <el-radio @click.native="editinps('Python')" label="Python"
                      :disabled="editinpDisabled.type"></el-radio>
            <el-radio @click.native="editinps('工作流')" label="工作流"
                      :disabled="editinpDisabled.type"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="editinpStatus.user_task_name" label="模板名称" prop="user_task_name">
          <el-input v-model="form.user_task_name"
                    auto-complete="off"
                    :disabled="editinpDisabled.user_task_name"></el-input>
        </el-form-item>
        <el-form-item v-if="editinpStatus.target_version" label="版本名称" prop="target_version">
          <el-select v-model="form.target_version" placeholder="请选择">
            <el-option v-for="item in versionOptions" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="editinpStatus.tenant_name" label="租户名称" prop="tenant_name">
          <el-select v-model="form.tenant_name" placeholder="请选择">
            <el-option v-for="item in tenantsOps" :label="item.tenant_name"
                       :value="item.tenant_name"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="editinpStatus.task_group_id" label="组名" prop="task_group_id">
          <el-select v-model="form.task_group_id" placeholder="请选择">
            <el-option v-for="item in taskGroupList"
                       :label="item.task_group_name"
                       :value="item.task_group_id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="editinpStatus.task_model" label="运行模式" prop="task_model">
          <el-select v-model="form.task_model" placeholder="请选择">
            <el-option v-for="item in modeOptions" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="editinpStatus.user_queue_name" label="队列名称" prop="user_queue_name">
          <el-select v-model="form.user_queue_name" placeholder="请选择">
            <el-option v-for="item in queueOptions" :label="item.name" :value="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="editinpStatus.task_timer_cron_exp" label="定时表示式" prop="task_timer_cron_exp">
          <!--<el-radio-group v-model="form.task_timer_cron_exp">
              <el-radio :label="3">是</el-radio>
              <el-radio :label="9">否</el-radio>
          </el-radio-group>-->
          <el-input v-model="form.task_timer_cron_exp" placeholder="0 0 3 * * ?" auto-complete="off"></el-input>
        </el-form-item>
        <!--<el-form-item v-if="editinpStatus.properties_files" label="属性文件路径" prop="properties_files">
            <UploadPath v-model="form.properties_files" uploadType="1"></UploadPath>
        </el-form-item>-->
        <el-form-item v-if="editinpStatus.attributes" label="添加属性" prop="attributes">
          <Attrinput v-model="form.attributes" type="1" :placeholder="attributesPlaceholder"></Attrinput>
          <!--<el-input v-model="form.ph" auto-complete="off"></el-input>-->
        </el-form-item>
        <el-form-item v-if="editinpStatus.files_files" label="配置文件" prop="files_files">
          <SelectPaths v-model="form.files_files"></SelectPaths>
        </el-form-item>
        <el-form-item v-if="editinpStatus.user_datasource_id" label="数据源" prop="user_datasource_id">
          <el-select v-model="form.user_datasource_id" placeholder="请选择数据源">
            <el-option v-for="item in datasourceOpts"
                       :label="datasourceFilter(item)"
                       :value="item.user_datasource_id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="editinpStatus.jars_files" label="应用程序jar包" prop="jars_files">
          <UploadPath v-model="form.jars_files" uploadType="1"></UploadPath>
        </el-form-item>
        <el-form-item v-if="editinpStatus.third_jars_files" label="第三方jars路径" prop="third_jars_files">
          <!--<UploadPath v-model="form.third_jars_files" uploadType="1"></UploadPath>-->
          <SelectPaths v-model="form.third_jars_files"></SelectPaths>
        </el-form-item>
        <!--<el-form-item v-if="editinpStatus.jobDir" label="指定job目录" prop="jobDir">
          <UploadPath v-model="form.jobDir" uploadType="1"></UploadPath>
        </el-form-item>-->
        <el-form-item v-if="editinpStatus.shell_files" label="脚本文件" prop="shell_files">
          <UploadPath v-model="form.shell_files" uploadType="1" :placeholder="shellPal"></UploadPath>
        </el-form-item>
        <el-form-item v-if="editinpStatus.main_script" label="Main脚本" prop="main_script">
          <el-input v-model="form.main_script" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="editinpStatus.properties" label="任务文件" prop="properties">
          <UploadPath v-model="form.properties" uploadType="1"></UploadPath>
        </el-form-item>
        <el-form-item v-if="editinpStatus.main_class" label="Main Class" prop="main_class">
          <el-input v-model="form.main_class" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="editinpStatus.params" label="添加参数" prop="params">
          <Attrinput v-model="form.params" type=2></Attrinput>
        </el-form-item>
        <el-form-item v-if="editinpStatus.shell_commands" label="命令" prop="shell_commands">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="form.shell_commands">
          </el-input>
        </el-form-item>

        <el-form-item v-if="editinpStatus.retry_times" label="重试次数" prop="retry_times">
          <el-select v-model="form.retry_times"  filterable="" allow-create placeholder="请选择或输入">
            <el-option v-for="item in retryTimesOpt" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="editinpStatus.task_desc" label="描述" prop="task_desc">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="form.task_desc">
          </el-input>
        </el-form-item>

        <!--<el-card v-show="editinpStatus.dateRadio" class="box-card">
            <div slot="header" class="clearfix">
                <span style="line-height: 36px;">定时选项</span>
                <el-radio-group v-model="form.dateRadio" style="float: right;line-height: 40px;">
                    <el-radio @click.native="editinps2(1)" label="1">简单配置</el-radio>
                    <el-radio @click.native="editinps2(2)" label="2">corn表达式配置</el-radio>
                </el-radio-group>
            </div>
            <el-form-item v-show="editinpStatus.dateFre" label="频率" prop="dateFre">
                <el-input placeholder="请输入内容" v-model="form.dateFre">
                    <el-select class="my-select-datet" v-model="form.dateType" slot="append">
                        <el-option label="分" value="1"></el-option>
                        <el-option label="时" value="2"></el-option>
                        <el-option label="日" value="3"></el-option>
                        <el-option label="周" value="4"></el-option>
                        <el-option label="月" value="5"></el-option>
                    </el-select>
                </el-input>
            </el-form-item>
            <el-form-item v-show="editinpStatus.dates" label="选择时间范围" prop="dates">
                <el-date-picker
                        v-model="form.dates"
                        type="datetimerange"
                        placeholder="选择时间范围">
                </el-date-picker>
            </el-form-item>
            <el-form-item v-show="editinpStatus.codeDate" label="定时表示式" prop="codeDate">
                <el-input v-model="form.codeDate" auto-complete="off"></el-input>
            </el-form-item>
        </el-card>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm">取 消</el-button>
        <el-button type="primary" @click="editSubmit" :loading="editLoading">{{btnEditText}}</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
  import util from '../../common/util'
  import C from '../../common/cfg'
  import Search from '../../components/Search.vue'
  import dao from '../../common/dao'
  import Attrinput from '../../components/Attrinput.vue'
  import SelectPaths from '../../components/SelectPaths.vue'
  import UploadPath from '../../components/UploadPath.vue'
  import NProgress from 'nprogress'
  import parser from 'cron-parser'
  import { mapGetters } from 'vuex'
  export default {
    components: {Attrinput, SelectPaths, UploadPath, Search},
    computed: {
      ...mapGetters([
        'getTenants',
        'getDataCenter'
      ])
    },
    data() {
      return {
        editinpDisabled: {
          type: true,
          user_task_name: true,
        },
        editinpStatus: {
          user_task_name: true,
          target_version: true,
          main_class: true,
          main_script: true,
          task_model: true,
          properties_files: true,
          attributes: true,
          tenant_name: true,
          user_queue_name: true,
          jars_files: true,
          third_jars_files: true,
          files_files: true,
          jobDir: true,
          shell_files: false,
          user_datasource_id: false,
          properties: false,
          params: true,
          shell_commands: false,
          task_timer_cron_exp: true,
          dateFre: true,
          dates: true,
          task_desc: true,
          retry_times: true,
          task_group_id: true,
        },
        queueOptions: [],
        versionOptions: [],
        datasourceOpts: [],
        modeOptions: [],
        rules: {
          user_task_name: [
            {required: true, message: '请输入模板名称！', trigger: 'blur'},
            {min: 1, max: 50, message: '长度在 1 到 50 个字符！', trigger: 'blur'},
            {validator: util.validateString, trigger: 'blur'},
            {validator: this.validateName, trigger: 'blur'}
          ],
          main_class: [
            {required: true, message: '请输入main_class！', trigger: 'blur'},
            {validator: util.validateFileName, trigger: 'blur'}
          ],
          main_script:[
            {required: true, message: '请输入main_class', trigger: 'blur'},
          ],
          user_datasource_id: [
            {type:'number', required: true, message: '请选择数据源！', trigger: 'change'}
          ],
          retry_times: [
            { required: true, message: '请选择重试次数！', trigger: 'change'},
            {validator: (rule, value, callback) => {
              if (/^([0-9])+$/.test(value)) { callback() }
              else callback(new Error('必须为数字'))
            }}
          ],
          task_group_id:[
            {type:'number', required: true, message: '请选择组名', trigger: 'change'}
          ],
          task_timer_cron_exp:[
            {
              validator: (rule, value, callback) => {
                if (value == '') { callback() }
                else {
                  try {
                    dao.cronValid({task_timer_cron_exp:value}).then(res=>{
                      if(res.FX.err){
                        callback(new Error('服务有误'))
                        return false;
                      }
                      if(res.body.isCronValid==1){
                        callback(new Error('表达式有误'));
                      }else {
                        callback();
                      }
                    })
                  } catch (err){
                    console.log('Error: ' + err.message);
                    callback(new Error('表达式有误'));
                  }
                }
              }, trigger: 'blur'
            }
          ],
          /*task_timer_cron_exp: [
            {
              validator: (rule, value, callback) => {
                if (value == '') { callback() }
                else {
                  try {
                    let interval = parser.parseExpression(value);
                    console.log('Date: ', interval.next().toString());
                    callback();
                  } catch (err){
                    console.log('Error: ' + err.message);
                    callback(new Error('表达式有误'));
                  }
                }
              }, trigger: 'blur'
            }
          ],*/
          jars_files: [{required: true, message: '请输入应用程序jar包', trigger: 'blur'}],
          target_version: [{required: true, message: '请选择版本', trigger: 'change'}],
          shell_files: [{required: true, message: '请选择脚本文件', trigger: 'change'}],
          task_model: [{required: true, message: '请选择模式', trigger: 'blur'}],
          user_queue_name: [{required: true, message: '请选择队列', trigger: 'change'}],
          shell_commands: [{required: true, message: '请输入命令', trigger: 'blur'}],
          tenant_name: [{required: true, message: '请选择租户', trigger: 'change'}],
          properties: [{required: true, message: '请选择任务文件', trigger: 'blur'}]
        },
        tenantsOps: [],
        editOpen: false,
        btnEditText: '保存',
        formTitle: '修改',
        formLabelWidth: '120px',
        form: {},
        butStatus: {
          update: true,
          add: false,
          rm: true,
        },
        formInline: {
          allOpts: [{
            key: 'user_task_name',
            label: '模板名称',
            type: '',
            val: ''
          },{
            key: 'task_group_name',
            label: '组名称',
            type: '',
            val: ''
          },{
            key: 'user_name',
            label: '用户',
            type: '',
            val: ''
          }, {
            key: 'task_run_component_type',
            label: '模版类型',
            type: 'sel',
            selOption: [{
              label: "Spark",
              value: "1"
            }, {
              label: "MapReduce",
              value: "2"
            }, {
              label: "Hive",
              value: "3"
            }, {
              label: "Sqoop",
              value: "4"
            }, {
              label: "Shell",
              value: "5"
            }, {
              label: "工作流",
              value: "6"
            }, {
              label: "Python",
              value: "7"
            }],
            val: ''
          }],
          cOpts: [{
            key: 'user_task_name',
            label: '模板名称',
            type: '',
            val: ''
          }]
        },
        dialogFormVisible: false,
        tableTitle: [{
          key: 'user_name',
          name: '用户',
        }, /* {
         key: 'role_names',
         name: '所属角色',
         },*/ {
          key: 'tenant_name',
          name: '租户名字'
        }, /* {
         key: 'data_center_name',
         name: '数据中心'
         },*/ {
          key: 'create_time',
          name: '创建时间',
        }, {
          key: 'update_time',
          name: '最近修改时间',
        }],
        tableData: [],
        pagination: {
          count: 0,
          start_index: 1,
          page_count: 20,
        },
        versionOptionsOfSYS: {},
        shellPal: '请选择路径',
        attributesPlaceholder: {
          key: 'key',
          val: 'value'
        },
        retryTimesOpt:[{
          value: '5',
          label: '5'
        },{
          value: '10',
          label: '10'
        },{
          value: '0',
          label: '0 - 非流式任务'
        }],
        uploadUrl: `${C.APIURL}bdpmng/service/task/batch/add`,
        headers: {
          Authentication: C.HEADERS.Authentication,
          RJDATACENTERID: `${util.fetch('dataCenterId')}`
        },
        uploadBody: {hdfs_dir: ''},
        taskGroupList:[],
      }
    },
    methods: {
      handleAvatarSuccess(response, file, fileList){

        if(response.retCode!='200') {
          this.$notify({
            title: '错误提示',
            message: `${response.retCode} : ${response.retMsg}`,
          });
          if (response.status == 401) this.$router.replace('/login');
          return false;
        }
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        this.getTaskHttp();
      },
      handleAvatarError(response, file, fileList){
        if (response.status == 401) {
          this.$router.replace('/login')
          return false
        }
        this.$notify({
          title: '错误提示',
          message: `${response.retCode} : ${response.retMsg}`,
        });

      },
      handlePreview(file){
      },
      handleRemove(file, fileList){
      },
      exportTask(){
        this.$confirm('确定要导出任务模板吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let ids = [];
          if((this.multipleSelection||[]).length>0){
            this.multipleSelection.map(item => {
              ids.push(item.user_task_id);
            });
          }
          return dao.batchDownload({"user_task_ids": ids})

        }).then((res)=>{
          if (res.bodyBlob.type != 'text/plain') {
            Message({
              type: 'error',
              message: res.body.retMsg
            });
            return false;
          }
          util.downloadFile('task.json', res.bodyBlob)
        });

      },
      async getlistTaskgroup(){
          let res =await dao.getlistTaskgroup({})
          if(res.FX.err) return false;
          this.taskGroupList = res.body.results
      },
      getUserTenantInfo(){
        dao.getUserTenantInfo({}).then(res => {
          if (res.FX.err) return false;
          this.tenantsOps = res.body.tenants || this.getTenants || [];
        })
      },
      getconfig(){
        dao.getconfig({"sys_conf_types": ["11", "12", "13", "14"]}).then(res => {
          if (res.FX.err) return false;
          let results = res.body.results || [];
          let versionOptions = {};
          results.map(item => {
            versionOptions[item.sys_conf_key] = util.versionDataFile(item);
          })
          this.versionOptionsOfSYS = versionOptions;
        });
      },
      datasourceFilter(item){
        item || (item = {});
        let type = item.dbtype == 1 ? 'mysql' : 'oracle';
        return `${type}-${item.datasource_name}`
      },
      getQueueOptions(){
        dao.getQueueListByUserId({}).then(res => {
          if (res.FX.err) return false;
          this.queueOptions = res.body.queueList || [{name: ''}]
        })
      },
      getDatasourceOpts () {
        dao.getDatasource({}).then(res => {
          if (res.FX.err)return false;
          this.datasourceOpts = res.body.results;
        }).catch()
      },
      vltest(val){
      },
      search(val){
        //调用查询服务
        this.getTaskHttp();
      },
      handleSizeChange (val) {
        this.pagination.page_count = val;
        this.getTaskHttp();
      },
      handleCurrentChange (val) {
        this.pagination.start_index = val;
        this.getTaskHttp();
      },
      currentChange (currentPage) {
        this.start_index = currentPage;
        this.getTaskHttp();
      },
      getEditinpShow () {
        return {
          Spark: ["user_task_name", "target_version", "main_class", "task_model", "properties_files", "attributes", "tenant_name", "user_queue_name", "jars_files", "third_jars_files", "files_files", "params", "task_timer_cron_exp", "dateFre", "dates","task_desc","retry_times","task_group_id"],
          MapReduce: ["user_task_name", "target_version", "main_class", "properties_files", "attributes", "user_queue_name", "tenant_name", "jars_files", "third_jars_files", "files_files", "params", "task_timer_cron_exp", "dateFre", "dates","task_desc","task_group_id"],
          Hive: ["user_task_name", "target_version", "user_queue_name", "shell_files", "tenant_name", "task_timer_cron_exp", "dateFre", "dates","task_desc","task_group_id"],
          Sqoop: ["user_task_name", "target_version", "user_queue_name", "shell_commands", "tenant_name", "user_datasource_id", "task_timer_cron_exp", "dateFre", "dates","task_desc","task_group_id"],
          Shell: ["user_task_name", "shell_files", "params", "main_script", "tenant_name", "task_timer_cron_exp", "dateFre", "dates","task_desc","task_group_id"],
          Python: ["user_task_name", "shell_files", "params", "main_script", "tenant_name", "task_timer_cron_exp", "dateFre", "dates","task_desc","task_group_id"],
          工作流: ["user_task_name", "jobDir", "dateFre", "tenant_name", "dates", "properties","task_desc","task_group_id"]
        }
      },
      updateEditInpStatus () {
        let type = this.form.type;
        let arr = this.getEditinpShow()[type];
        for (let key in this.editinpStatus) {
          if (arr.indexOf(key) > -1) this.editinpStatus[key] = true;
          else this.editinpStatus[key] = false;
        }
      },
      updateEditVersion(){
        let versionOptions = this.versionOptionsOfSYS;
        this.form.target_version = "";
        this.versionOptions = versionOptions[this.form.type] || [];
      },
      updateEditModeOptions(){
        let modeOptions = {
          Spark: [{
            label: 'yarn-cluster',
            value: '1'
          }, {
            label: 'yarn-client',
            value: '2'
          },],
        };
        this.form.task_model = "";
        this.modeOptions = modeOptions[this.form.type] || [];
      },
      updateTips () {
        switch (this.form.type) {
          case 'Python':
            this.shellPal = '请选择py或者zip文件';
            this.rules.shell_files = [{required: true, message: '请选择脚本文件', trigger: 'change'},
              {
                validator: (rule, value, callback) => {
                  let re = /\.(?:py|zip)$/i
                  if (!re.test(value)) callback(new Error('只能选择py或者zip文件'));
                  else callback()
                }, trigger: 'blur'
              }]
            break;
          case 'Shell':
            this.shellPal = '请选择sh或者zip文件';
            this.rules.shell_files = [{required: true, message: '请选择脚本文件', trigger: 'change'},
              {
                validator: (rule, value, callback) => {
                  let re = /\.(?:sh|zip)$/i
                  if (!re.test(value)) callback(new Error('只能选择sh或者zip文件'));
                  else callback()
                }, trigger: 'blur'
              }]
            break;
          default:
            this.shellPal = '请选择路径';
            this.rules.shell_files = [{required: true, message: '请选择脚本文件', trigger: 'change'}]
            break;
        }
      },
      editinps (t) {
        this.form.type = t;
        this.updateEditInpStatus();
        this.updateEditVersion();
        this.updateEditModeOptions();
        this.updateTips()
      },
      editinps2 (t) {
        switch (t) {
          case 1:
            this.editinpStatus.dateFre = true;
            this.editinpStatus.dates = true;
            this.editinpStatus.codeDate = false;
            break;
          case 2:
            this.editinpStatus.dateFre = false;
            this.editinpStatus.dates = false;
            this.editinpStatus.codeDate = true;
            break;
          default:
            break;
        }
      },
      cgFormInpDisabled (boo) {
        for (let i in this.editinpDisabled) {
          this.editinpDisabled[i] = boo;
        }
      },
      num2type(num){
        num = parseInt(num);
        let arr = ['Spark', 'MapReduce', 'Hive', 'Sqoop', 'Shell', '工作流', 'Python'];
        return arr[num - 1]
      },
      /**
       * spark: 应用程序jar包->jars_files 1
       * spark: 第三方jars路径->jars_files 6 多个
       * hive: 脚本文件->sql_files;
       * shell: 脚本文件->shell_files 2 /8 zip;
       * python: 脚本文件->python_files 3;
       * 工作流: 指定job目录->hdfs_dir 不用,待定
       * 工作流: 任务文件 -> job_files 4
       * @param body
       */
      form2req(body){
        if (body.attributes) {
          let attributes = [];
          attributes = body.attributes.map(item => {
            let obj = {}
            obj[item.key] = item.val
            return obj
          });
          body.attributes = attributes;
        }
        if (body.params) {
          body.params = body.params.map(item => {
            return item.val
          })
        }
        if (body.jars_files) {
          body.jars_files = util.hdfsPath2Jsom(body.jars_files, 1)
        }
        /* if (body.third_jars_files != void 0) {
         body.third_jars_files = util.hdfsPath2Jsom(body.third_jars_files, 6)
         }*/
        if (body.properties_files != void 0) {
          body.properties_files = util.hdfsPath2Jsom(body.properties_files, 4);
        }
        if (body.jobDir != void 0) {
          body.hdfs_dir = body.jobDir;
          body.jobDir = undefined;
        }
        if (body.shell_files != void 0) {
          if (body.task_run_component_type == 3) {
            body.sql_files = util.hdfsPath2Jsom(body.shell_files, 7);
            body.shell_files = void 0;
          }
          else if (body.task_run_component_type == 7) {
            body.python_files = util.hdfsPath2Jsom(body.shell_files, 3);
            body.shell_files = void 0;
          }
          else body.shell_files = util.hdfsPath2Jsom(body.shell_files, 2);
        }
        if (body.properties != void 0) {
          body.job_files = util.hdfsPath2Jsom(body.properties, 4);
          body.properties = void 0;
        }

        if (body.main_script != void 0) {
          body.main_class = body.main_script;
          body.main_script = void 0;
        }
        if(body.retry_times){
          if(body.retry_times > 0){
            body.is_streaming_task = 0
          }else body.is_streaming_task = 1
        }
      },
      res2form(res){
        if (res.params) {
          res.params = res.params.map(item => {
            return {key: '', val: item}
          });
        }
        if (res.attributes) {
          let arr = [];
          (res.attributes instanceof Array) ? '' : (res.attributes = [])
          let attributes = res.attributes
          for (let i in attributes) {
            let resObj = attributes[i];
            if (!resObj) continue;
            let obj = {}
            for (let key in resObj) {
              obj = {key: key, val: resObj[key]};
            }
            arr.push(obj);
          }
          res.attributes = arr;
        }

        if (res.shell_files != void 0) {
          let tmp = (res.shell_files||[])[0] || {};
          res.shell_files = tmp.hdfs_file_path || '';
        }
        let tmp;
        switch (res.task_run_component_type) {
          case '7':
            tmp = (res.python_files||[])[0] || {};
            res.shell_files = tmp.hdfs_file_path || '';
            break;
          case '3':
            tmp = (res.sql_files||[])[0] || {};
            res.shell_files = tmp.hdfs_file_path || '';
            break;
        }
        if (res.properties_files != void 0) {
          let tmp = (res.properties_files||[])[0] || {};
          res.properties_files = tmp.hdfs_file_path || '';
        }
        if (res.hdfs_dir != void 0) {
          res.jobDir = res.hdfs_dir;
        }
        if (res.job_files != void 0) {
          let tmp = (res.job_files||[])[0] || {};
          res.properties = tmp.hdfs_file_path || '';
        }

        if (res.jars_files != void 0) {
          /*let jars_files = '';
           for (let item of res.jars_files) {
           if (item.file_type == 1) {
           res.jars_files = item.hdfs_file_path
           }
           }*/
          let tmp = (res.jars_files||[])[0] || {};
          res.jars_files = tmp.hdfs_file_path || '';
        }

        /*   if (res.third_jars_files != void 0) {
         let tmp = res.third_jars_files[0] || {};
         res.third_jars_files = tmp.hdfs_file_path || '';
         }*/

        if (res.main_class != void 0) {
          res.main_script = res.main_class
        }
        if(res.retry_times!=void 0){
          res.retry_times = `${res.retry_times}`
        }
      },
      getFormDefault(){
        this.form = {
          task_result:'',
          user_task_final_status:'',
          task_desc:'',
          taskGroupName:'',
          user_task_id: '',
          user_task_type: "1",//类型 1是单一 2 工作流
          task_run_component_type: "",//任务运行的组件
          user_task_name: "",
          target_version: '',
          main_class: '',
          task_model: '',
          tenant_name: '',
          user_queue_name: "",//队列
          main_script: '',
          attributes: [],
          third_jars_files: [],
          files_files: [],
          jarsOther: '',
          user_datasource_id: '',
          task_timer_cron_exp: '',//定时表达式
          properties: "",
          type: 'Spark',
          properties_files: '',
          task_group_id:'',
          task_desc: '',
          retry_times:'0',
          params: []
        };
      },
      handleUpdate () {

        let user_task_id = this.multipleSelection[0].user_task_id || '';
        if (user_task_id == '') {return false}
        let user_task_ids = [user_task_id];
        dao.getByTaskID({user_task_ids: user_task_ids}).then(res => {
          if (res.FX.err) return false;
          let results = res.body.results;
          if (results.length != 1) {
            this.$message('返回无效数据');
            return false;
          }
          let form = res.body.results[0];
          //处理form 需要的内容
          this.res2form(form);
          this.editinps(this.num2type(form.task_run_component_type));
          for (let i in form) this.form[i] = form[i];
          this.form.user_datasource_id = parseInt(this.form.user_datasource_id);
          //打开form前准备
          this.cgFormInpDisabled(true);
          this.formTitle = "修改";
          this.dialogFormVisible = true;
        })
      },
      /**
       * task_run_component_type
       * 任务运行的组件
       1:spark
       2:mapreduce
       3:hive
       4:sqoop
       5:shell
       6:ooz
       7:python
       8:hive sql 稽查任务
       **/
      organizeData () {
        let type = this.form.type;
        let fun = "";
        let body = {};
        let formArr = this.getEditinpShow()[type];
        if (type == "Spark") {
          fun = (this.form.user_task_id == '') ? "taskSparkAdd" : 'taskSparkUpdate';
          body.task_run_component_type = 1;
        } else if (type == "MapReduce") {
          fun = (this.form.user_task_id == '') ? "taskMrAdd" : 'taskMrUpdate';
          body.task_run_component_type = 2;
        } else if (type == "Hive") {
          fun = (this.form.user_task_id == '') ? "taskHiveAdd" : "taskHiveUpdate";
          body.task_run_component_type = 3;
        } else if (type == "Sqoop") {
          fun = (this.form.user_task_id == '') ? "taskSqoopAdd" : "taskSqoopUpdate";
          body.task_run_component_type = 4;
        } else if (type == "Shell") {
          fun = (this.form.user_task_id == '') ? "taskShellAdd" : "taskShellUpdate";
          body.task_run_component_type = 5;
        } else if (type == "Python") {
          fun = (this.form.user_task_id == '') ? "taskPythonAdd" : "taskPythonUpdate";
          body.task_run_component_type = 7;
        } else if (type == "工作流") {
          fun = (this.form.user_task_id == '') ? "taskWorkflowAdd" : "taskWorkflowUpdate";
          body.task_run_component_type = 6;
        } else return false;
        formArr.map(item => {
          body[item] = this.form[item]
        });
        body = JSON.parse(JSON.stringify(body));
        //个性调整
        body.user_task_type = 1;
        if (type == "工作流") {
          body.user_task_type = 2
        }
        //默认需要添加
        body.user_task_id = this.form.user_task_id;
        body.data_center_id = this.form.data_center_id;
        if (body.data_center_id == undefined) body.data_center_id = this.getDataCenter.data_center_id || '';//vuex 获取
        //结构转换
        this.form2req(body);
        this.editLoading = true;
        this.btnEditText = '保存中';
        dao[fun](body).then(res => {
          this.editLoading = false;
          this.btnEditText = '保存';
          if (res.FX.err) return false;
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          //关闭修改页,
          this.dialogFormVisible = false;
          this.getTaskHttp();
        }).catch(res => {
          this.editLoading = false;
          this.btnEditText = '保存';

        });
      },
      editSubmit () {
        this.$refs.form.validate((valid) => {
          if (!valid) return false;
          //提示创建或修改
          let act = "创建";
          this.$confirm(`此操作将${act}任务, 是否继续?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }).then(() => {
            this.organizeData();
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            });
          });
        })
      },
      updateButStatus (val) {
        if (val.length == 1) {
          this.butStatus.update = false;
          this.butStatus.rm = false;
        } else if (val.length == 0) {
          this.butStatus.update = true;
          this.butStatus.rm = true;
        } else {
          this.butStatus.update = true;
          this.butStatus.rm = false;
        }

        for(let item of val){
          if (item.status == 0||item.task_status == 1||item.task_status == 4) {
            this.butStatus.rm = true
            break;
          }
        }


      },
      handleSelectionChange (val) {

        this.multipleSelection = val;
        this.updateButStatus(val);

      },
      changeTimeStart (i) {
        this.tableData[i].timing = this.tableData[i].timing == '1' ? "0" : "1";
      },
      /**
       * 任务的执行状态
       * 0 无运行
       1：运行中
       2：已终止
       3：完成
       * @param scope
       */
      changeStart (scope) {

        let row = scope.row || {};
        let i = scope.$index;
        let title, fun;
        fun = this.tableData[i].task_status == '1' ? ( title = "停止该一次性任务模版", fun = 'stopTask' ) : (title = "启动该一次性任务模版", fun = 'startTask');
        if (this.tableData[i].task_run_type == '2')
          fun = this.tableData[i].status == '0' ? ( title = "禁用该定时模版", fun = 'diableTask' ) : (title = "启用该定时模版", fun = 'enableTask');
        this.$confirm(`确认${title}吗?`, '提示', {}).then(() => {
          return dao[fun]({user_task_id: row.user_task_id})
        }).then(res => {
          if (res.FX.err) return false;
          this.$message({
            message: '启动成功!',
            type: 'success'
          });
          this.getTaskHttp();
        });

      },
      handleAdd () {
//        this.$refs.form.resetFields();
        this.cgFormInpDisabled();
        this.editinps("Spark");
        this.getFormDefault();
        this.formTitle = "创建";
        this.form.user_task_id == ''
        this.dialogFormVisible = true
      },
      handleDelete () {
        this.$confirm('此操作将删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let ids = [];
          this.multipleSelection.map(item => {
            ids.push(item.user_task_id);
          });
          return dao.deleteTask({"user_task_ids": ids})
        }).then((res) => {
          if (res.FX.err) return false;
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getTaskHttp();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      hdfsPath2Jsom(hdfs_dir){
        [{
          file_id: '',
          file_name: '',
          hdfs_file_path: hdfs_dir || ''
        }]
      },
      gotopage (p) {
        if(p==311){
          this.$router.push({path: `/page${p}/all`, query: {allTaskDetail: '1'}});
        }else this.$router.push(`/page${p}`);
      },
      getTaskHttp(){

        let conditions = {};
        let cOpts = this.formInline.cOpts || [];
        cOpts.map(item => {
          conditions[item.key] = [item.val]
        });

        conditions.task_run_component_type = (conditions.task_run_component_type || [])[0] || ''

        let arg = {
          conditions,
          start_index: this.pagination.start_index,
          page_count: this.pagination.page_count
        };
        //arg.conditions = conditions;
        dao.getTask(arg).then(response => {
          if (response.FX.err) return false;
          this.pagination.count = response.body.count;
          this.tableData = response.body.results
        })
      },
      validateName (rule, value, callback) { //验证任务名称是否重复
        if (this.editinpDisabled.user_task_name) {
          callback()
          return false
        }
        if (!value) {
          callback(new Error('请输入任务模板名称'));
        } else {
          dao.validateAuditTaskName({"audit_task_name": value}).then((response) => {
            if (response.body.retMsg != "1") {
              callback(new Error('任务名称重复'));
            }
            callback();
          })
        }
      },
      resetForm () { //重置表单
        this.$refs.form.resetFields();
        this.dialogFormVisible = false;
      }
    },
    mounted () {
      this.getlistTaskgroup()
      this.getUserTenantInfo();
      this.getconfig();
      this.getDatasourceOpts();
      this.getFormDefault();
      this.getQueueOptions();
      this.getTaskHttp();

    },
    beforeDestroy () {

    }
  }
</script>

<style scoped>
  .my-select-datet {
    width: 70px;
  }

  .el-select {
    width: 100%;
  }

  .toolbar .el-form-item {
    margin-bottom: 10px;
  }

  .toolbar {
    background: #fff;
    padding: 10px 10px 0px 10px;
  }

  span.zhHelpTips {
    color: #13CE66;
  }

  span.zhHelpTipsErr {
    color: #FF4949;
  }

  form.el-form {
    padding: 0 10px;
  }
</style>